package com.yznote.cloudesk.config.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.yznote.cloudesk.common.pojo.Result;
import com.yznote.cloudesk.common.pojo.User;
import com.yznote.cloudesk.common.utils.IPUtils;
import com.yznote.cloudesk.config.JWTconfig;
import com.yznote.cloudesk.common.tokenShare.YTokenShare;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author : xiaozhoutongxue
 * @date : 2022/10/14 13:24
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private static ObjectMapper objectMapper =new ObjectMapper();
@Autowired
    YTokenShare yTokenShare;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不拦截嗅探请求
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }

        String yToken = request.getHeader("yToken");
        String cookieToken = null;
        if(request.getCookies()!=null) {
            for (Cookie cookie : request.getCookies()) {
                if ("yToken".equals(cookie.getName())) {
                    cookieToken = cookie.getValue();
                    break;
                }
            }
        }
        String paramToken = null;
        paramToken = request.getParameter("yToken");
        if (yToken == null&&cookieToken==null&&paramToken==null) {
            fasleResult(response,"[error]没有token，请重试");
            return false;
        }
        User user;
        if ((user=JWTconfig.verifyToken(paramToken))!=null||(user = JWTconfig.verifyToken(cookieToken))!=null||(user=JWTconfig.verifyToken(yToken))!=null) {
            String requestIp = IPUtils.getRequestIp();
            user.setLastLoginIp(requestIp);
            yTokenShare.put(user);
            return true;
        } else {
            fasleResult(response,"[error]验证token错误或者过期，请重试");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        yTokenShare.delete();
    }

    public static void fasleResult(HttpServletResponse response, String mes) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(objectMapper.writeValueAsString(Result.build(null,403,mes)));
        writer.close();
        response.flushBuffer();
    }

}
